<?php

namespace utils;

/**
 * Created by PhpStorm.
 * User: Duyonggao
 * Date: 2017/5/26 0026
 * Time: 下午 3:42
 * 高效转链的淘宝key
 */
use app\models\AuthorizeToken;
use yii\base\Exception;
use Yii;

class TaoBaoGxApi
{
    public $c;
    /**
     * @var string 高效转链的淘宝key，只用于高效转链功能。
     */
    public $appkey = '23225630';
    public $secretKey = '93fee8926d98bfb23c05628f701c4b0d';

    /**
     * @var string 转淘口令用的key
     */
    public $appkeyCode = '24685201';
    public $secretKeyCode = '17309c9c57ddc3ec60bd1b73cde727fd';


    const PUBLIC_REDIRECT_URI = 'http://www.qingtaoke.com/oauth';//授权回调地址
    const PUBLIC_REDIRECT_CMS_URI = 'http://www.qingtaoke.com/oauthcms';//授权回调地址

    public $no_cache = false;

    public function __construct()
    {
        /**
         * SDK工作目录
         * 存放日志，TOP缓存数据
         */
        if (!defined("TOP_SDK_WORK_DIR"))
        {
            define("TOP_SDK_WORK_DIR", Yii::$app->getRuntimePath()."/taobao/tmp/");
        }

        /**
         * 是否处于开发模式
         * 在你自己电脑上开发程序的时候千万不要设为false，以免缓存造成你的代码修改了不生效
         * 部署到生产环境正式运营后，如果性能压力大，可以把此常量设定为false，能提高运行速度（对应的代价就是你下次升级程序时要清一下缓存）
         */
        if (!defined("TOP_SDK_DEV_MODE"))
        {
            define("TOP_SDK_DEV_MODE", true);
        }

        if (!defined("TOP_AUTOLOADER_PATH"))
        {
            define("TOP_AUTOLOADER_PATH", dirname(__FILE__)."/taobao/");
        }
        require_once (TOP_AUTOLOADER_PATH."Autoloader.php");
    }

    /**
     * @author       :   DuYongGao
     * @name         :   getPrivilegeTbk
     * @description  :
     * @param $item_id
     * @param $adId
     * @param $sId
     * @param $token
     * @return mixed|ResultSet|SimpleXMLElement
     */
    public function getPrivilegeTbk($item_id,$adId,$sId,$token){
        $this->c = new \TopClient;
        $this->c->appkey = $this->appkey;
        $this->c->secretKey = $this->secretKey;
        $this->c->format="json";
        $req = new \TbkPrivilegeGetRequest;
        $req->setItemId($item_id);
        $req->setAdzoneId($adId); //B pid 第三位
        $req->setPlatform("1");
        $req->setSiteId($sId);//A pid 第二位
        $resp = $this->c->execute($req, $token);
        return $resp;
    }


    /**
     * 授权地址
     * @return string
     */
//    public function createOauthUrl(){
//        $token_check = mt_rand(111111, 999999);
//        Yii::$app->session['token_check'] = $token_check;
//        $client_id = $this->appkey;
//        $api ='https://oauth.taobao.com/authorize';//正式地址
//        $str = $api . '?response_type=code&client_id=' . $client_id . '&redirect_uri=' . urlencode(self::PUBLIC_REDIRECT_URI) . '&state='.$token_check.'&view=';
//        $str .= Util::isM()?'wap':'web';
//        return $str;
//
//    }

    /**
     * 授权地址
     * @return string
     */
//    public function createOauthUrlCms(){
//        $token_check = mt_rand(111111, 999999);
//        Yii::$app->session['token_check'] = $token_check;
//        $client_id = $this->appkey;
//        $api ='https://oauth.taobao.com/authorize';//正式地址
//        $str = $api . '?response_type=code&client_id=' . $client_id . '&redirect_uri=' . urlencode(self::PUBLIC_REDIRECT_CMS_URI) . '&state='.$token_check.'&view=web';
//
//        return $str;
//
//    }

    /**
     * @author       :   DuYongGao
     * @name         :   tokenCheck
     * @description  :检查状态
     * @param $token_check
     * @return bool
     */
//    public function tokenCheck($token_check){
//        return Yii::$app->session['token_check'] == $token_check && !empty($token_check) ? true :false;
//    }

    /**根据code 获取token
     * @param $code
     * @return array|bool
     */
//    public function getTokenByCode($code){
//        $client_id = $this->appkey;
//        $client_secret = $this->secretKey;
//        $url = 'https://oauth.taobao.com/token';//正式地址
//        $postfields= array('grant_type'=>'authorization_code',
//            'client_id'=>$client_id,
//            'client_secret'=>$client_secret,
//            'code'=>$code,
//            'redirect_uri'=>self::PUBLIC_REDIRECT_URI);
//        $post_data = '';
//
//        foreach ($postfields as $key => $value) {
//            $post_data .= "$key=" . urlencode($value) . "&";
//        }
//
//        $ch = curl_init();
//        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
//        curl_setopt($ch, CURLOPT_URL, $url);
//        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//        curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
//        curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
//
//        //指定post数据
//        curl_setopt($ch, CURLOPT_POST, true);
//
//        //添加变量
//        curl_setopt($ch, CURLOPT_POSTFIELDS, substr($post_data,0,-1));
//        $output = curl_exec($ch);
//        curl_close($ch);
//        if(!empty($output)){
//            $output = json_decode($output,true);
//            if(!empty($output['refresh_token'])&&!empty($output['access_token'])){
//                return [
//                    'token' => $output['access_token'],
//                    'refresh_token' => $output['refresh_token'],
//                    'taobao_user_nick' => isset($output['taobao_user_nick']) ? urldecode($output['taobao_user_nick']) : '',
//                    'taobao_user_id' => isset($output['taobao_user_id']) ? $output['taobao_user_id'] : '',
//                ];
//            }
//        }
//        return false;
//    }
//
//    /**根据$refresh_token  更新
//     * @param $refresh_token
//     * @return array
//     */
//    public function getTokenByRefresh($refresh_token){
//
//        $client_id = $this->appkey;
//        $client_secret = $this->secretKey;
//        $url = 'https://oauth.taobao.com/token';//正式地址
//        $postfields= array('grant_type'=>'refresh_token',
//            'client_id'=>$client_id,
//            'client_secret'=>$client_secret,
//            'refresh_token'=>$refresh_token
//        );
//        $post_data = '';
//
//        foreach ($postfields as $key => $value) {
//            $post_data .= "$key=" . urlencode($value) . "&";
//        }
//
//        $ch = curl_init();
//        curl_setopt($ch, CURLOPT_URL, $url);
//        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
//        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//        curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
//        curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
//
//        //指定post数据
//        curl_setopt($ch, CURLOPT_POST, true);
//
//        //添加变量
//        curl_setopt($ch, CURLOPT_POSTFIELDS, substr($post_data,0,-1));
//        $output = curl_exec($ch);
//        curl_close($ch);
//
//        if(!empty($output)){
//            $output = json_decode($output,true);
//            if(!empty($output['refresh_token'])&&!empty($output['access_token'])){
//
//                return [
//                    'token' => $output['access_token'],
//                    'refresh_token' => $output['refresh_token'],
//                    'taobao_user_nick' => isset($output['taobao_user_nick']) ?  urldecode( $output['taobao_user_nick']) : '',
//                    'taobao_user_id' => isset($output['taobao_user_id']) ? $output['taobao_user_id'] : '',
//                ];
//            }
//        }
//        return false;
//
//    }
//

    /**
     * @author       :   DuYongGao
     * @name         :   getToken
     * @description  :获取高效转链的token
     * @return array|bool|mixed|null
     */
    public function getToken(){
        $uid = $this->uid();
        /**
         * 数据库也没有就是真没有了，需要授权
         */
//        $row = \app\models\QtkCmsToken::findOne(['uid'=>$uid,'is_enable'=>1,'source'=>1]);
        $row = AuthorizeToken::findOne(['qtk_uid'=>$uid]);
        if(empty($row)){
            return false;
        }
        $data = [
            'uid' => $row['qtk_uid'],
            'taobao_user_id' => $row['taobao_user_id'],
            'taobao_user_nick' => $row['taobao_user_nick'],
            'token' => $row['token'],
            'refresh_token' => $row['refresh_token'],
        ];
        return $data;
    }

    public function getTokenCache($cache = true){
        $key = "getTokenCache5".date('Y-m-d');
        $token = Yii::$app->request->get($key);
        if(empty($token) || !$cache){
            $token = $this->getToken();
            if(!empty($token)){
                Yii::$app->cache->set($key,$token,86400);
            }
        }
        return $token;
    }

    /**
     * @return int
     * 17187460525 123456 162784
     */
    public function uid(){
//        return 62475;
        return 162784;
    }

    /**
     * @author       :   DuYongGao
     * @name         :   transferGx
     * @description  :高效转链
     * @param $gid
     * @param $pid
     * @param $re_try
     * @return array
     * @throws Exception
     */
    public function transferGx($gid , $pid , $re_try = true){
        $token = $this->getTokenCache();
        if(empty($token) || empty($token['token'])){
            throw new Exception("您还未授权",91001);
        }
        $uid = $this->uid();

        $pid_key = md5('err' . $token['token'].$pid.$uid);
        $pid_expire = 3600;//
        $pid_err = Yii::$app->cache->get($pid_key);
        if(!empty($pid_err)){
            throw new Exception("请使用授权账号下的PID",91003);
        }

        $key = md5('apilink' . $gid . $pid . $uid . $token['taobao_user_id']);
        $expire = 7200;//高效转连缓存时间
        $pwd = Yii::$app->cache->get($key);
        if (!empty($pwd) && !$this->no_cache) {
            return $pwd;
        }
        
        if(!preg_match('/^mm_(\d+)_(\d+)_(\d+)$/',$pid,$out)){
            throw new Exception("PID格式不正确",91004);
        }else{
            $adId = $out[3];
            $sId = $out[2];
        }
        $resp = $this->getPrivilegeTbk($gid,$adId,$sId,$token['token']);
        if(isset($resp->result->data->coupon_click_url)){
            $data = (array) $resp->result->data;
            Yii::$app->cache->set($key, $data , $expire);
            return $data;
        }else{
            if (isset($resp->code)) {
                if (isset($resp->sub_code) && ($resp->sub_code == 'isp.special-campaign-error')) {
                    throw new Exception("定向计划服务异常,请稍后重试",91005);
                } elseif (isset($resp->sub_code) && ($resp->sub_code == 'isv.item-not-exist')) {
                    throw new Exception("该商品已经下架",91006);
                } elseif (isset($resp->sub_code) && ($resp->sub_code == 'isv.pid-not-correct')) {
                    Yii::$app->cache->set($pid_key, 1, $pid_expire);
                    throw new Exception("请使用授权账号下的PID",91007);
                } elseif (isset($resp->sub_code) && ($resp->sub_code == 'isv.appkey-total-limit')) {
                    throw new Exception("接口调用达到上限",91011);
                } elseif (isset($resp->sub_code) && ($resp->sub_code == 'invalid-sessionkey')) {
                    throw new Exception("授权登陆无效，或者已经过期",91008);
                } else {
                    throw new Exception("计划申请失败，请稍后再试",91009);
                }
            }
            throw new Exception("计划申请失败，请稍后再试",91010);
        }
    }


    public function getTaoCode($params){
        if(strlen($params['title']) > 100){
            $params['title'] = mb_strcut($params['title'],0,100).'...';
        }
        if(mb_strlen($params['title']) < 5){
            $params['title'] = $params['title'] . '　　　　　　　';
        }
        
        $this->c = new \TopClient;
        $this->c->appkey = $this->appkeyCode;
        $this->c->secretKey = $this->secretKeyCode;
        $req = new \TbkTpwdCreateRequest;
        $req->setUserId("1");
        $req->setText($params['title']);
        $req->setUrl($params['url']);
        if(isset($params['pic_url'])){
            $req->setLogo($params['pic_url']);
        }else{
            $req->setLogo("");
        }
        $req->setExt("{}");
        $resp = $this->c->execute($req);
        $result = (array)$resp;
        if(!isset($result["data"])){
            throw new Exception("官方接口数据出错，请稍后再试！");
        }
        $result["data"] = (array) $result["data"];
        if(!isset($result["data"]['model'])){
            throw new Exception("官方接口数据出错，请稍后再试！");
        }
        return $result['data']['model'];
    }

    /**
     * @author       :   DuYongGao
     * @name         :   transferGx
     * @description  :高效转链
     * @param $gid
     * @param $pid
     * @param $re_try
     * @return array
     * @throws Exception
     */
//    public function sysGx($gid , $pid , $re_try = true){
//        $uid = $this->getSysUid();
//
//        $token = $this->getSysToken($uid);
//        if(empty($token) || empty($token['token'])){
//            throw new Exception("您还未授权",91001);
//        }
//
//        $pid_key = md5('err' . $token['token'].$pid.$uid);
//        $pid_expire = 3600;//
//        $pid_err = Yii::$app->cache->get($pid_key);
//        if(!empty($pid_err)){
//            throw new Exception("请使用授权账号下的PID",91003);
//        }
//
//        $key = md5('apilink' . $gid . $pid . $uid . $token['taobao_user_id']);
//        $expire = 7200;//高效转连缓存时间
//        $pwd = Yii::$app->cache->get($key);
//        if (!empty($pwd)) {
//            return $pwd;
//        }
//
//        $api = new TaoBaoGxApi();
//        if(!preg_match('/^mm_(\d+)_(\d+)_(\d+)$/',$pid,$out)){
//            throw new Exception("PID格式不正确",91004);
//        }else{
//            $adId = $out[3];
//            $sId = $out[2];
//        }
//        $resp = $api->getPrivilegeTbk($gid,$adId,$sId,$token['token']);
//        if(isset($resp->result->data->coupon_click_url)){
//            $data = (array) $resp->result->data;
//            Yii::$app->cache->set($key, $data , $expire);
//            return $data;
//        }else{
//            if (isset($resp->code)) {
//
//                if (isset($resp->sub_code) && ($resp->sub_code == 'isp.special-campaign-error')) {
//                    if ($re_try == true) {
//                        return $this->transferGx($gid , $pid , false);
//                    }
//                    throw new Exception("定向计划服务异常,请稍后重试",91005);
//                } elseif (isset($resp->sub_code) && ($resp->sub_code == 'isv.item-not-exist')) {
//
//                    /**
//                     * 商品不存在的后续处理
//                     */
//                    $this->goodNotExit($gid);
//                    throw new Exception("该商品已经下架",91006);
//                } elseif (isset($resp->sub_code) && ($resp->sub_code == 'isv.pid-not-correct')) {
//
//                    Yii::$app->cache->set($pid_key, 1, $pid_expire);
//
//                    throw new Exception("请使用授权账号下的PID",91007);
//                } elseif (isset($resp->sub_code) && ($resp->sub_code == 'isv.appkey-total-limit')) {
//                    throw new Exception("接口调用达到上限",91011);
//                } elseif (isset($resp->sub_code) && ($resp->sub_code == 'invalid-sessionkey')) {
//
//                    self::saveToken(['token' => '', 'refresh_token' => '', 'taobao_user_id' => $token['taobao_user_id'], 'taobao_user_nick' => $token['taobao_user_nick']], $uid);
////                    Yii::log('计划申请失败1'.var_export($resp,true).var_export($token,true),CLogger::LEVEL_ERROR);
//                    throw new Exception("授权登陆无效，或者已经过期",91008);
//                } else {
//                    Yii::log('计划申请失败2'.var_export($resp,true).var_export($token,true),CLogger::LEVEL_ERROR);
//                    throw new Exception("计划申请失败，请稍后再试",91009);
//                }
//
//            }
//            throw new Exception("计划申请失败，请稍后再试",91010);
//        }
//    }


//    public function doError($code,$msg){
//
//        switch($code){
//            case 91001://未授权
//                $api = new TaoBaoGxApi();
//                $data = [
//                    'msg'=> $msg,
//                    'code' => $code,
//                    'auth_url' => $api->createOauthUrl(),
//                ];
//                break;
//            case 91006://商品下架
//                //code
//                $data = [
//                    'msg'=> $msg,
//                    'code' => $code,
//                ];
//                break;
//            case 91003://请使用授权账号下的PID
//            case 91007://请使用授权账号下的PID
//            case 91008://授权登陆无效，或者已经过期
//                $data = [
//                    'msg'=> $msg,
//                    'code' => $code,
//                    'auth_url' => $this->createOauthUrl(),
//                ];
//                break;
//            default:
//                $data = [
//                    'msg' => $msg,
//                    'code' => $code,
//                ];
//        }
//
//        return $data;
//    }




}